package smokesignals.data;

import com.google.common.collect.Maps;
import com.googlecode.recycled.data.WithId;

import java.util.Map;

/**
 * @author Henryk Konsek
 */
public class IdAssignerDataStoreEventListener<T> extends EmptyDataStoreEventListener<T> {

    protected IdAssigner<T> defaultIdAssigner;

    protected Map<Class<?>, IdAssigner<T>> idAssignersForClasses = Maps.newHashMap();

    public IdAssignerDataStoreEventListener(IdAssigner<T> defaultIdAssigner,
                                            Map<Class<?>, IdAssigner<T>> idAssignersForClasses) {
        this.defaultIdAssigner = defaultIdAssigner;
        this.idAssignersForClasses = idAssignersForClasses;
    }

    @Override
    public void beforeStore(WithId<T> withId) {
        if (withId instanceof WithAssignableId) {
            if (idAssignersForClasses.containsKey(withId.getClass())) {
                idAssignersForClasses.get(withId.getClass()).assignId((WithAssignableId<T>) withId);
            } else if (defaultIdAssigner != null) {
                defaultIdAssigner.assignId((WithAssignableId<T>) withId);
            }
        }
    }

}
